<template>
  <Dialog
    v-model="dialogVisible"
    maxHeight="60vh"
    width="80vw"
    :title="t('common.title.selectCustomer')"
    :before-close="() => closeDialog()"
    class="mobile-dialog"
  >
    <!--    顶部查询项-->
    <el-form :model="form" inline class="mobile-form">
      <el-form-item :label="t('wholesalOrder.customerName')">
        <el-input
          v-model="form.cusname"
          clearable
          :placeholder="t('wholesalOrder.customerName')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('wholesalOrder.email')">
        <el-input
          v-model="form.email"
          clearable
          :placeholder="t('wholesalOrder.email')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item>
        <div class="mobile-button-group horizontal">
          <el-button type="primary" icon="Search" @click="search">{{
            t('common.query')
          }}</el-button>
          <el-button icon="Refresh" @click="reset(true)">{{ t('common.reset') }}</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 移动端卡片视图 -->
    <div v-if="isMobile" class="mobile-card">
      <el-card v-for="item in dataList" :key="item.id" class="customer-card">
        <template #header>
          <div class="card-header">
            <span class="customer-name">{{ item.cusname }}</span>
            <el-checkbox
              :model-value="multipleSelection.some((selected) => selected.id === item.id)"
              @change="(checked: boolean) => handleCardSelection(item, checked)"
            />
          </div>
        </template>

        <div class="card-content">
          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.phone') }}:</span>
            <span class="value">{{ item.phone || '-' }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.email') }}:</span>
            <span class="value">{{ item.email || '-' }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('customer.role') }}:</span>
            <span class="value">
              {{
                item.role === 'user' ? '普通用户' : item.role === 'distributor' ? '经销商' : '其他'
              }}
            </span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('wholesalOrder.creationTime') }}:</span>
            <span class="value">{{ item.create_time || '-' }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 桌面端表格视图 -->
    <div v-else class="mobile-table">
      <el-table
        class="m-t-10px"
        :data="dataList"
        highlight-current-row
        stripe
        border
        ref="tableRef"
        v-loading="tableLoading"
        row-key="id"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :reserve-selection="true" width="55" />
        <el-table-column
          :label="t('wholesalOrder.customerName')"
          prop="cusname"
          min-width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.phone')"
          prop="phone"
          min-width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.email')"
          prop="email"
          min-width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('customer.role')"
          prop="role"
          min-width="200"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ row.role === 'user' ? '普通用户' : row.role === 'distributor' ? '经销商' : '其他' }}
          </template>
        </el-table-column>

        <el-table-column
          :label="t('wholesalOrder.creationTime')"
          prop="create_time"
          min-width="200"
          :show-overflow-tooltip="true"
        />
      </el-table>
    </div>

    <!--    分页-->
    <Pagination
      class="mobile-table"
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="getList"
    />
    <template #footer>
      <div class="mobile-button-group horizontal">
        <el-button class="m-r-4" @click="closeDialog"
          >{{ t('system.parameterConfig.cancel') }}
        </el-button>
        <el-button type="primary" @click="submit">{{ t('wholesalOrder.add') }}</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import Pagination from '@/components/Pagination/index.vue'
import { getCustomerListApi } from '@/api/wholesalOrder'
import { Dialog } from '@/components/Dialog'
import { ElMessage } from 'element-plus'
import { useAppStore } from '@/store/modules/app'

const props = withDefaults(defineProps<{ multiple?: boolean }>(), {
  multiple: false
})
const emit = defineEmits(['exposeMultipleData'])
const { t } = useI18n()
const tableRef = ref()
const appStore = useAppStore()

// 移动端检测
const isMobile = computed(() => appStore.getMobile)

const isReset = ref<boolean>(false)
const dialogVisible = ref<boolean>(false)
const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const selectionPak = ref<any[]>([])

const paginationTotal = ref<number>(0)
const form = ref<Record<string, any>>({
  cusname: '',
  email: '',
  pageIndex: 1,
  pageSize: 15
})

// 移动端卡片选择处理
const handleCardSelection = (item: any, checked: boolean) => {
  if (checked) {
    if (props.multiple) {
      // 多选模式
      if (!multipleSelection.value.some((selected) => selected.id === item.id)) {
        multipleSelection.value.push(item)
      }
    } else {
      // 单选模式
      multipleSelection.value = [item]
    }
  } else {
    multipleSelection.value = multipleSelection.value.filter((selected) => selected.id !== item.id)
  }
}

//批量勾选
const handleSelectionChange = (val: any[]) => {
  if (val.length > 1 && !props.multiple) {
    // 如果选中的行数超过一行， 并且不允许多选，清除之前的选中项，只保留最新的选中项
    const latestSelection = val[val.length - 1]
    tableRef.value.clearSelection()
    tableRef.value.toggleRowSelection(latestSelection, true)
    multipleSelection.value = [latestSelection]
  } else {
    multipleSelection.value = val
  }
}
//点击添加按钮
const submit = () => {
  if (!multipleSelection.value.length)
    return ElMessage.warning(t('common.selectText') + ' ' + t('dealerAssetManagement.customer'))
  if (!props.multiple && multipleSelection.value.length > 1)
    return ElMessage.warning('最多只能勾选一位客户')
  if (props.multiple && isReset.value) {
    const merge = selectionPak.value.concat(multipleSelection.value)
    emit('exposeMultipleData', deduplication(merge))
  } else {
    emit('exposeMultipleData', multipleSelection.value)
  }
  closeDialog()
}

//一维数组去重
const deduplication = (val: any[], key?: string) => {
  if (!val || !val.length) return
  return val.reduce((acc, item) => {
    if (!acc.some((x: Record<string, any>) => x[key ?? 'id'] === item[key ?? 'id'])) {
      acc.push(item)
    }
    return acc
  }, [])
}

//点击取消关闭弹框
const closeDialog = () => {
  reset()
  dialogVisible.value = false
}

//初始化请求
const getList = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  params.role = currentRole.value
  delete params.date
  const resp = await getCustomerListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}
const search = () => {
  form.value.pageIndex = 1
  getList()
}
//重置查询项
const reset = (isRequest?: boolean) => {
  form.value = {
    cusname: '',
    email: '',
    pageIndex: 1,
    pageSize: 15
  }
  paginationTotal.value = 0
  multipleSelection.value = []
  nextTick(() => {
    if (tableRef?.value) {
      tableRef.value.clearSelection()
    }
  })
  if (isRequest) {
    getList()
    isReset.value = true
  }
}
// val 为选中的数据
// role 为角色
const currentRole = ref<string>('user')
const initialize = (val: any[], role?: string) => {
  currentRole.value = role ?? 'user'
  getList()
  if (props.multiple) selectionPak.value = val
  if (!val || !val.length) return
  console.log('val', val)
  val.forEach((item: Record<string, any>) => {
    nextTick(() => {
      if (tableRef?.value) {
        // 详情返回和客户列表返回的客户对象不一致，处理一下
        let itemSet = Object.assign({}, item, {
          cusname: item.username,
          partner:
            typeof item.partner == 'string'
              ? item.partner.split(',').map((i) => Number(i))
              : item.partner,
          owner_id: item.owner
        })
        tableRef.value.toggleRowSelection(itemSet, true)
      }
    })
  })
}

defineExpose({
  dialogVisible,
  initialize
})
</script>

<style lang="less" scoped>
@media (width <= 768px) {
  .customer-card {
    margin-bottom: 12px;

    .card-header {
      .customer-name {
        font-size: 13px;
      }
    }

    .card-content {
      .info-row {
        margin-bottom: 6px;

        .label {
          min-width: 70px;
          font-size: 12px;
        }

        .value {
          font-size: 12px;
        }
      }
    }
  }
}

.customer-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .customer-name {
      margin-right: 12px;
      font-size: 14px;
      font-weight: 600;
      flex: 1;
    }
  }

  .card-content {
    .info-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      font-size: 13px;

      .label {
        min-width: 80px;
        font-weight: 500;
        color: #666;
      }

      .value {
        color: #333;
        text-align: right;
        flex: 1;
      }
    }
  }
} // 移动端客户卡片样式
</style>
